package glossos.tree.snapshot;

import glossos.tree.Node;
import glossos.tree.factory.NodeFactory;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.jmock.lib.legacy.ClassImposteriser;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;

public class NodeMapper implements ParameterizedRowMapper<Node> {
    private NodeRepository nodeRepository;

    public NodeMapper(NodeRepository nodeRepository) {
		this.nodeRepository = nodeRepository;
    }

	public Node mapRow(ResultSet resultSet, int i) throws SQLException {
        Node node = new Node();
        node.setId(resultSet.getLong("id"));
        node.setFrequency(resultSet.getInt("frequency"));
        node.setWord(resultSet.getString("word"));
        node.setParent(createNodeProxy(resultSet.getLong("parent_id")));
        node.setChildren(new PersistentNodeMap(node, nodeRepository));
        return node;
    }

    private Node createNodeProxy(Long parentId) {
    	return parentId != 0
    		? ClassImposteriser.INSTANCE.imposterise(new NodeProxy(nodeRepository, parentId), Node.class)
    		: null;
    }
}
